import {
  ActionType,
  ModalForm,
  PageContainer,
  ProColumns,
  ProForm,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProTable
} from "@ant-design/pro-components";
import {Button, Flex, Form, Image, Popconfirm, Tooltip} from "antd";
import React, {useRef, useState} from "react";
import {
  DeleteOutlined,
  EditOutlined,
  FileImageOutlined,
  PlusOutlined,
  SettingFilled,
  SketchOutlined,
  SolutionOutlined,
  UnlockOutlined
} from "@ant-design/icons";
import {
  worker_head_img_url,
  worker_health_certificate_url,
  worker_id_card_back_url,
  worker_id_card_front_url
} from "@/services/admin-api/aliyun";
import AliyunUpload from "@/components/Upload/AliyunUpload";
import {
  dictList,
  globalApi,
  globalLoadTableApi,
  globalLoadTableApiCode,
  handleGloblApi
} from "@/services/admin-api/globalApi";
import MapContainer from "@/components/AMap/MapContainer";
import MapAutoComplete from "@/components/AMap/MapAutoComplete";
import {Access, useAccess} from "umi";

export type Worker = {
  workerId: number;
  workerUuid: string;
  workerType: number;
  workerStatus: number;
  workerNickName: string;
  workerRealName: string;
  workerPhone: string;
  workerIdCardNumber: string;
  workerIdCardFrontUrl: string;
  workerIdCardBackUrl: string;
  workerHeadImgUrl: string;
  workerLoginPassword: string;
  workerLoginPasswordSalt: string;
  workerEmergencyContact: string;
  workerEmergencyContactPhone: string;
  workerNation: number;
  workerSex: number;
  workerAge: number;
  workerAddress: string;
  workerAddressLng: number;
  workerAddressLat: number;
  workerHealthCertificateUrl: string;
  workerYear: number;
  workerCity: string;
  workerSkills: string;
  workerTools: string;
  wrokerLevel: number;
  delFlag: boolean;
  createTime: string;
  createUserId: number;
  createUserName: string;
  updateTime: string;
  updateUserId: number;
  updateUserName: string;
  storeId: number;
  storeName: string;
};

export const workerType = [
  {label: '收纳师', value: 0,},
  {label: '小哥', value: 1,},
  {label: '司机', value: 2,},
  {label: '搬家公司', value: 3,},
]

export const workerLevel = [
  {label: '实习生', value: 0,},
  {label: '整理师', value: 1,},
  {label: '方案师', value: 2,},
  {label: '规划师', value: 3,},
]

export const workerStatus = [
  {label: '注册', value: 0,},
  {label: '启用', value: 1,},
  {label: '冻结', value: 2,},
]

export const workerStatusEnum = {
  0: {text: '注册', status: 'Processing',},
  1: {text: '启用', status: 'Success',},
  2: {text: '冻结', status: 'Error',},
}

export const workerSex = [
  {label: '女', value: 0,},
  {label: '男', value: 1,},
]

export const worker_skills = await dictList('worker_skills')
export const worker_tools = await dictList('worker_tools')

export const citySelect = await globalApi('/config/citySelect', {})

const storeSelect = await globalApi('/store/select', {})

export const workerNation = [
  {label: "汉族", value: 1},
  {label: "壮族", value: 2},
  {label: "回族", value: 3},
  {label: "藏族", value: 4},
  {label: "维吾尔族", value: 5},
  {label: "苗族", value: 6},
  {label: "彝族", value: 7},
  {label: "蒙古族", value: 8},
  {label: "布依族", value: 9},
  {label: "朝鲜族", value: 10},
  {label: "满族", value: 11},
  {label: "侗族", value: 12},
  {label: "瑶族", value: 13},
  {label: "白族", value: 14},
  {label: "土家族", value: 15},
  {label: "哈尼族", value: 16},
  {label: "哈萨克族", value: 17},
  {label: "傣族", value: 18},
  {label: "黎族", value: 19},
  {label: "傈僳族", value: 20},
  {label: "佤族", value: 21},
  {label: "畲族", value: 22},
  {label: "高山族", value: 23},
  {label: "拉祜族", value: 24},
  {label: "水族", value: 25},
  {label: "东乡族", value: 26},
  {label: "纳西族", value: 27},
  {label: "景颇族", value: 28},
  {label: "柯尔克孜族", value: 29},
  {label: "土族", value: 30},
  {label: "达斡尔族", value: 31},
  {label: "仫佬族", value: 32},
  {label: "羌族", value: 33},
  {label: "布朗族", value: 34},
  {label: "撒拉族", value: 35},
  {label: "毛南族", value: 36},
  {label: "仡佬族", value: 37},
  {label: "锡伯族", value: 38},
  {label: "阿昌族", value: 39},
  {label: "普米族", value: 40},
  {label: "塔吉克族", value: 41},
  {label: "怒族", value: 42},
  {label: "乌孜别克族", value: 43},
  {label: "俄罗斯族", value: 44},
  {label: "鄂温克族", value: 45},
  {label: "德昂族", value: 46},
  {label: "保安族", value: 47},
  {label: "裕固族", value: 48},
  {label: "京族", value: 49},
  {label: "塔塔尔族", value: 50},
  {label: "独龙族", value: 51},
  {label: "鄂伦春族", value: 52},
  {label: "赫哲族", value: 53},
  {label: "门巴族", value: 54},
  {label: "珞巴族", value: 55},
  {label: "基诺族", value: 56},
  {label: "其他", value: 99}
]

export const skillsToStr = (skillss: string) => {
  const skills = skillss.split(",").map(v => Number(v))
  const r: string[] = []
  worker_skills.data.forEach((e: any) => {
    skills.forEach((e1: any) => {
      if (e.value === e1) {
        r.push(e.label)
      }
    })
  })
  return r.join(',')
}

export const toolsToStr = (toolss: string) => {
  const skills = toolss.split(",").map(v => Number(v))
  const r: string[] = []
  worker_tools.data.forEach((e: any) => {
    skills.forEach((e1: any) => {
      if (e.value === e1) {
        r.push(e.label)
      }
    })
  })
  return r.join(',')
}

export default () => {

  const access = useAccess()

  const [modalOpen, handleModalOpen] = useState(false);
  const [modalStatusOpen, handleStatusModalOpen] = useState(false);
  const [modalLevelOpen, handleLevelModalOpen] = useState(false);
  const [form] = Form.useForm();
  const [statusForm] = Form.useForm();
  const [levelForm] = Form.useForm();
  const actionRef = useRef<ActionType>();

  const [visible, setVisible] = useState(false);
  const [imgUrl, setImgUrl] = useState<string>();

  const mapRef = useRef<any>();

  const imageFragment = (url: any, objId: any, objType: any) => {
    if (!url) {
      const props = {
        objId, objType, back: () => {
          actionRef.current?.reload()
        }
      }
      return <AliyunUpload {...props} />
    }
    return <Flex gap="small" wrap="wrap">
      <Button
        size={"small"} icon={<FileImageOutlined/>}
        onClick={() => {
          setImgUrl('https://bdq-cloud.oss-cn-shenzhen.aliyuncs.com' + url)
          setVisible(true)
        }}/>
      <Access accessible={access.canAuth('worker:edit')}>
        <Popconfirm
          title="删除图片" description="确认删除这张图片？" okText="Yes" cancelText="No"
          onConfirm={async () => {
            await globalApi('/attachment/remove', {objId, objType})
            actionRef.current?.reload()
          }}>
          <Button size={'small'} danger icon={<DeleteOutlined/>}/>
        </Popconfirm>
      </Access>
    </Flex>;
  }

  const columns: ProColumns<Worker>[] = [
    {title: 'ID', dataIndex: 'workerId', valueType: 'digit'},
    {title: '编码', dataIndex: 'workerUuid', valueType: 'text', ellipsis: true},
    {title: '类型', dataIndex: 'workerType', valueType: 'select', fieldProps: {options: workerType,}},
    {title: '状态', dataIndex: 'workerStatus', valueType: 'select', valueEnum: workerStatusEnum},
    {title: '昵称', dataIndex: 'workerNickName', valueType: 'text'},
    {title: '姓名', dataIndex: 'workerRealName', valueType: 'text'},
    {
      title: '店铺',
      dataIndex: 'storeId',
      valueType: 'select',
      fieldProps: {options: storeSelect.data, showSearch: true},
    },
    {title: '等级', dataIndex: 'workerLevel', valueType: 'select', fieldProps: {options: workerLevel,}},
    {
      title: '技能',
      dataIndex: 'workerSkills',
      valueType: 'select',
      fieldProps: {options: worker_skills.data,},
      render: (_, record) => skillsToStr(record.workerSkills)
    },
    {
      title: '工具',
      dataIndex: 'workerTools',
      valueType: 'select',
      fieldProps: {options: worker_tools.data,},
      render: (_, record) => toolsToStr(record.workerTools)
    },
    {
      title: '手机号',
      dataIndex: 'workerPhone',
      valueType: 'text',
      fieldProps: {autoComplete: "new-password"},
      ellipsis: true
    },
    {title: 'workerLoginPassword', dataIndex: 'workerLoginPassword', valueType: 'text', hideInSearch: true},
    {title: 'workerLoginPasswordSalt', dataIndex: 'workerLoginPasswordSalt', valueType: 'text', hideInSearch: true},
    {title: '身份证号', dataIndex: 'workerIdCardNumber', valueType: 'text', ellipsis: true,},
    {title: '紧急联系人', dataIndex: 'workerEmergencyContact', valueType: 'text', ellipsis: true},
    {
      title: '联系人电话',
      dataIndex: 'workerEmergencyContactPhone',
      valueType: 'text',
      fieldProps: {autoComplete: "new-password"}, ellipsis: true
    },
    {
      title: '民族',
      dataIndex: 'workerNation',
      valueType: 'select',
      fieldProps: {options: workerNation, showSearch: true}
    },
    {title: '性别', dataIndex: 'workerSex', valueType: 'select', fieldProps: {options: workerSex,}},
    {title: '年龄', dataIndex: 'workerAge', valueType: 'digit', hideInSearch: true},
    {
      title: '地址',
      dataIndex: 'workerAddress',
      valueType: 'text',
      ellipsis: true,
      fieldProps: {autoComplete: "new-password"}
    },
    {title: 'workerAddressLng', dataIndex: 'workerAddressLng', valueType: 'digit', hideInSearch: true},
    {title: 'workerAddressLat', dataIndex: 'workerAddressLat', valueType: 'digit', hideInSearch: true},
    {title: '工作年限', dataIndex: 'workerYear', valueType: 'digit', hideInSearch: true},
    {
      title: '城市编码',
      dataIndex: 'workerCity',
      valueType: 'select',
      fieldProps: {options: citySelect.data, showSearch: true}
    },
    {
      title: '人像面', dataIndex: 'workerIdCardFrontUrl', valueType: 'text', hideInSearch: true,
      render: (_, record) => imageFragment(record.workerIdCardFrontUrl, record.workerId, worker_id_card_front_url)
    },
    {
      title: '国徽面', dataIndex: 'workerIdCardBackUrl', valueType: 'text', hideInSearch: true,
      render: (_, record) => imageFragment(record.workerIdCardBackUrl, record.workerId, worker_id_card_back_url)
    },
    {
      title: '头像', dataIndex: 'workerHeadImgUrl', valueType: 'text', hideInSearch: true,
      render: (_, record) => imageFragment(record.workerHeadImgUrl, record.workerId, worker_head_img_url)
    },
    {
      title: '健康证', dataIndex: 'workerHealthCertificateUrl', valueType: 'text', hideInSearch: true,
      render: (_, record) => imageFragment(record.workerHealthCertificateUrl, record.workerId, worker_health_certificate_url)
    },
    {title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '创建用户ID', dataIndex: 'createUserId', valueType: 'digit', hideInSearch: true,},
    {title: '创建用户', dataIndex: 'createUserName', valueType: 'text', hideInSearch: true,},
    {title: '更新时间', dataIndex: 'updateTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '更新用户ID', dataIndex: 'updateUserId', valueType: 'digit', hideInSearch: true,},
    {title: '更新用户', dataIndex: 'updateUserName', valueType: 'text', hideInSearch: true,},
    {
      title: <SettingFilled/>, width: 150,
      render: (_, record) => [
        <Access accessible={access.canAuth('worker:edit')}>
          <Tooltip title="编辑"><Button
            key={'edit_' + record.workerId} size="small" icon={<EditOutlined/>} type="primary"
            onClick={async () => {
              form.setFieldsValue({
                ...record,
                workerSkillsList: record.workerSkills ? record.workerSkills.split(",").map((v) => Number(v)) : [],
                workerToolsList: record.workerTools ? record.workerTools.split(",").map((v) => Number(v)) : [],
                store: {label: record.storeName, value: record.storeId}
              });
              handleModalOpen(true);
            }}
          /></Tooltip>
          <Tooltip title="修改状态">
            <Button
              key={'editstatus_' + record.workerId} size="small" icon={<SolutionOutlined/>} type="primary"
              onClick={async () => {
                // form.setFieldsValue({...record});
                // handleModalOpen(true);
                handleStatusModalOpen(true)
                statusForm.setFieldsValue({...record})
              }}
            /></Tooltip>
          <Tooltip title="修改等级">
            <Button
              key={'editlevel_' + record.workerId} size="small" icon={<SketchOutlined/>} type="primary"
              onClick={async () => {
                // form.setFieldsValue({...record});
                // handleModalOpen(true);
                handleLevelModalOpen(true)
                levelForm.setFieldsValue({...record})
              }}
            /></Tooltip>
          <Tooltip title="重置密码">
            <Popconfirm
              title="重置密码" description="确认重置密码？" okText="Yes" cancelText="No" key={`pop_${record.workerId}`}
              onConfirm={async () => {
                // await globalApi('/attachment/remove', {objId, objType})
                await globalApi('/worker/resetPwd', {workerId: record.workerId, workerPhone: record.workerPhone})
                actionRef.current?.reload()
              }}>
              <Button size={'small'} danger icon={<UnlockOutlined/>}/>
            </Popconfirm></Tooltip>
        </Access>

        // <Flex align="flex-start" gap="small" vertical>
        //   <Dropdown.Button menu={{
        //     items: [
        //       {
        //         key: '1',
        //         label: '编辑',
        //       },
        //       {
        //         key: '2',
        //         label: '审核',
        //       },
        //       {
        //         key: '3',
        //         label: '重置密码',
        //       },
        //     ], onClick: (e) => {
        //       console.log('click', e);
        //     }
        //   }}></Dropdown.Button>
        // </Flex>
      ],
      valueType: 'option',
    },
  ];

  const loadWorkerMarker = () => {
    const formData = form.getFieldsValue()
    if (formData.workerAddressLat && formData.workerAddressLng) {
      const AMap = mapRef.current?.AMapC()
      mapRef.current?.addMarker(new AMap.LngLat(formData.workerAddressLng, formData.workerAddressLat))
    }
  }

  return <PageContainer header={{title: '', breadcrumb: {},}}>
    <ProTable<Worker>
      columns={columns} actionRef={actionRef} size={"small"}
      search={{span: 4}}
      headerTitle={
        <Access accessible={access.canAuth('worker:add')}>
          <Button
            key="primary" type="primary" icon={<PlusOutlined/>} onClick={() => {
            handleModalOpen(true)
          }}/>
        </Access>
      }
      request={async (param) => globalLoadTableApiCode('/worker/table', 'worker:list:search', access, param)}
      rowKey={(record) => record.workerId}
      columnsState={{
        defaultValue: {
          workerAddressLng: {show: false},
          workerAddressLat: {show: false},
          workerLoginPassword: {show: false},
          workerLoginPasswordSalt: {show: false},
          delFlag: {show: false},
          createUserId: {show: false},
          createUserName: {show: false},
          createTime: {show: false},
          updateUserId: {show: false},
          updateUserName: {show: false},
          updateTime: {show: false},
        }
      }}/>

    <ModalForm
      modalProps={{destroyOnClose: true}} autoFocusFirstInput submitTimeout={15000}
      width="800px" open={modalOpen} onOpenChange={handleModalOpen} form={form}
      onFinish={async (value) => {
        console.log('value = ', value);
        let success = await handleGloblApi('/worker/saveOrUpdate', value)

        if (success) {
          actionRef.current?.reload();
          return true
        }

      }}
    >
      <ProForm.Item>
        <MapContainer ref={mapRef} init={loadWorkerMarker}/>
      </ProForm.Item>

      <ProFormDigit label="ID" name="workerId" hidden/>
      <ProForm.Group>
        <MapAutoComplete
          label="地址" rules={[{required: true}]} name="workerAddress" style={{width: 328}}
          mapRef={mapRef} latLnt={(latLng: any) => {
          form.setFieldsValue({workerAddressLat: latLng.lat, workerAddressLng: latLng.lng})
        }}/>
        <ProFormSelect label="类型" rules={[{required: true}]} name="workerType" options={workerType}/>
        <ProFormSelect label="性别" rules={[{required: true}]} name="workerSex" options={workerSex}/>
        <ProFormSelect label="民族" rules={[{required: true}]} name="workerNation" showSearch options={workerNation}/>
      </ProForm.Group>
      <ProForm.Group>
        <ProFormText label="昵称" rules={[{required: true}]} name="workerNickName"/>
        <ProFormText label="姓名" rules={[{required: true}]} name="workerRealName"/>
        <ProFormText
          fieldProps={{autoComplete: "new-password"}} label="手机号" rules={[{required: true}]}
          name="workerPhone"/>
      </ProForm.Group>
      <ProForm.Group>
        <ProFormDigit label="年龄" rules={[{required: true}]} name="workerAge"/>
        <ProFormText label="身份证号" rules={[{required: true}]} name="workerIdCardNumber"/>
        <ProFormSelect label="城市" rules={[{required: true}]} name="workerCity" showSearch options={citySelect.data}/>
        {
          form.getFieldValue("workerLoginPassword") ? '' : <ProForm.Group>
            <ProFormText.Password
              label="密码" rules={[{required: true}]} initialValue={"123456"} width={"xs"}
              name="workerLoginPassword"/>
          </ProForm.Group>
        }
      </ProForm.Group>
      <ProForm.Group>
        <ProFormDigit label="工作年限" rules={[{required: true}]} name="workerYear"/>
        <ProFormText label="紧急联系人" rules={[{required: true}]} name="workerEmergencyContact"/>
        <ProFormText
          fieldProps={{autoComplete: "new-password"}} label="联系人电话" rules={[{required: true}]}
          name="workerEmergencyContactPhone"/>
      </ProForm.Group>
      <ProForm.Group>
        <ProFormSelect label="技能" name="workerSkillsList" mode={"multiple"} options={worker_skills.data}/>
        <ProFormSelect label="工具" name="workerToolsList" mode={"multiple"} options={worker_tools.data}/>

        <ProFormDigit name="storeId" hidden/>
        <ProFormText name="storeName" hidden/>
        <ProFormSelect
          name={"store"} label={"店铺"} showSearch options={storeSelect.data}
          fieldProps={{
            labelInValue: true, onSelect: (value) => {
              form.setFieldsValue({storeId: value.value, storeName: value.label})
            }
          }}/>
      </ProForm.Group>

      <ProFormDigit label="workerAddressLng" name="workerAddressLng" hidden/>
      <ProFormDigit label="workerAddressLat" name="workerAddressLat" hidden/>
    </ModalForm>

    <ModalForm
      modalProps={{destroyOnClose: true}} submitTimeout={15000}
      width="400px" open={modalStatusOpen} onOpenChange={handleStatusModalOpen} form={statusForm}
      onFinish={async (value) => {
        console.log('value = ', value);
        let success = await handleGloblApi('/worker/modifyStatus', value)

        if (success) {
          actionRef.current?.reload()
          return true
        }

      }}
    >
      <ProFormDigit label="ID" name="workerId" hidden/>
      <ProFormSelect label="状态" rules={[{required: true}]} name="workerStatus" options={workerStatus}/>
    </ModalForm>

    <ModalForm
      modalProps={{destroyOnClose: true}} submitTimeout={15000}
      width="400px" open={modalLevelOpen} onOpenChange={handleLevelModalOpen} form={levelForm}
      onFinish={async (value) => {
        console.log('value = ', value);
        let success = await handleGloblApi('/worker/modifyLevel', value)

        if (success) {
          actionRef.current?.reload()
          return true
        }

      }}
    >
      <ProFormDigit label="ID" name="workerId" hidden/>
      <ProFormSelect label="等级" rules={[{required: true}]} name="workerLevel" options={workerLevel}/>
    </ModalForm>

    <div style={{display: 'none'}}>
      <Image.PreviewGroup preview={{visible, onVisibleChange: (vis) => setVisible(vis)}}>
        {/*{imageList.map(image => (<Image key={'image_' + image.id} src={image.path}/>))}*/}
        <Image src={imgUrl}/>
      </Image.PreviewGroup>
    </div>

  </PageContainer>
}
